package com.example.demo.config.token;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;

import com.example.demo.bean.User;

/**
 * 获取security中用户信息的类
 * 
 * @author Administrator
 *
 */
public class TokenUtils {

	private static SecurityContextLogoutHandler logoutHandler = new SecurityContextLogoutHandler();

	/**
	 * 获取当前登录的用户User对象
	 * 
	 * @return
	 */
	public static User getToken() throws Exception {
		User token = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		return token;
	}

	/**
	 * 获取当前用户NAME
	 * <p>
	 * 这里并没有用到userToken，那个包装了原本的类，推荐用，但我们的demo里面的user不完善，所以没有用
	 * 
	 * @return
	 */
	public static String getNickname() throws Exception {
		return getToken().getUsername();
	}

	/**
	 * 获取当前用户ID
	 * 
	 * @return
	 */
	public static Integer getUserId() throws Exception {
		return getToken() == null ? null : getToken().getId();
	}

	/**
	 * 退出登录
	 * 
	 * @param request
	 * @param response
	 */
	public static void logout(HttpServletRequest request, HttpServletResponse response) {
		logoutHandler.logout(request, response, SecurityContextHolder.getContext().getAuthentication());
	}
}
